package com.fjp.heartguard.ui.userinfo

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.RoundedCornersTransformation
import com.fjp.heartguard.R
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.data.bean.CredentialFile
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.ext.dp
import com.fjp.heartguard.app.ext.init
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.app.util.AppUtils
import com.fjp.heartguard.app.util.DateTimeUtil
import com.fjp.heartguard.app.weight.pop.EditCertificatePop
import com.fjp.heartguard.app.weight.pop.TakePhotoPop
import com.fjp.heartguard.databinding.ActivityUserinfoBinding
import com.fjp.heartguard.ui.userinfo.adapter.CertificateAdapter
import com.fjp.heartguard.viewmodel.UserinfoViewModel
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.OptionPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.UnitDateFormatter
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import com.yalantis.ucrop.UCrop
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.dp2px
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.time.LocalDate


class UserinfoActivity : BaseActivity<UserinfoViewModel, ActivityUserinfoBinding>() {
    private val REQUEST_LOCATION_PERMISSION = 1
    val takePhotoCode = 200
    val takeAlbumCode = 201
    val ucropCode = 202
    lateinit var birthdayPicker: DatePicker
    fun listener(index: Int, item: CredentialFile) {
        showEditDialog(index, item)
    }

    val certificaterAdapter = CertificateAdapter(arrayListOf<CredentialFile>(), this::listener)

    private fun showEditDialog(index: Int, item: CredentialFile) {
        XPopup.Builder(this).dismissOnTouchOutside(false).dismissOnBackPressed(false).isDestroyOnDismiss(true).autoOpenSoftInput(false).popupWidth(400.dp.toInt()).asCustom(EditCertificatePop(this, item, index, object : EditCertificatePop.Listener {

            override fun onclickDelete(index: Int) {
                val userInfo = mViewModel.userInfo.get()
                userInfo?.credential_files?.removeAt(index)
                mViewModel.userInfo.set(userInfo)
                mViewModel.userInfo.notifyChange()
                certificaterAdapter.removeAt(index)
            }

            override fun onclickSave(name: String) {
                val userInfo = mViewModel.userInfo.get()
                userInfo?.credential_files?.get(index)?.name = name
                userInfo?.credential_files?.get(index)?.time = DateTimeUtil.formatDate(System.currentTimeMillis(), DateTimeUtil.DATE_PATTERN_SS)
                mViewModel.userInfo.set(userInfo)
                certificaterAdapter.setList(mViewModel.userInfo.get()?.credential_files)
                certificaterAdapter.notifyDataSetChanged()
            }

        })).show()
    }
    private fun showNoLocationPop() {
        XPopup.Builder(this).asConfirm("提示", "当前手机没有开启定位服务，是否去开启", "否", "是", {
            val intent: Intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivity(intent)
        }, {}, false).show()
    }
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mViewModel.title.set("个人信息")
        mViewModel.showRightText.set(true)
        mDatabind.click = ClickProxy()
        mViewModel.userInfo.set(App.userInfo.copy())
        if(mViewModel.userInfo.get()!!.birthday.isEmpty()){
            mViewModel.userInfo.get()!!.birthday = "1970-01-01"
        }
        mDatabind.sexRg.setOnCheckedChangeListener { radioGroup, i ->
            mViewModel.userInfo.get()?.sex = if (i == R.id.manRb) "男" else "女"
        }
        if (App.userInfo.sex == "女") {
            mDatabind.womanRb.isChecked = true
        } else {
            mDatabind.manRb.isChecked = true
        }

        mViewModel.address.value = App.userInfo.address
        if (App.userInfo.province.isNotEmpty()) {
            mDatabind.provinceEt.setText("${App.userInfo.province}-${App.userInfo.city}-${App.userInfo.district}")
        }
        if (App.userInfo.has_participation == 1) {
            mDatabind.attendYesRb.isChecked = true
        } else {
            mDatabind.attendNoRb.isChecked = true
        }
        if (App.userInfo.has_exercise == 1) {
            mDatabind.trainingYesRb.isChecked = true
        } else {
            mDatabind.trainingNoRb.isChecked = true
        }


        findViewById<TextView>(R.id.rightTv).setOnClickListener {
            val tempUserInfo = mViewModel.userInfo.get()
            if (tempUserInfo!!.name.trim().isEmpty()) {
                showToast("请输入姓名")
                return@setOnClickListener
            }
            if (tempUserInfo!!.birthday.trim().isEmpty()) {
                showToast("请选择出生日期")
                return@setOnClickListener
            }
            if (tempUserInfo!!.qualification.trim().isEmpty()) {
                showToast("请选择教育程度")
                return@setOnClickListener
            }
            if (tempUserInfo!!.speciality.trim().isEmpty()) {
                showToast("请输入专业")
                return@setOnClickListener
            }
            if (tempUserInfo!!.career.trim().isEmpty()) {
                showToast("请输入从事职业")
                return@setOnClickListener
            }
            if (tempUserInfo!!.work_time.trim().isEmpty()) {
                showToast("请选择从业时长")
                return@setOnClickListener
            }
            if (tempUserInfo!!.city.trim().isEmpty()) {
                showToast("请选择居住地")
                return@setOnClickListener
            }
            if (tempUserInfo!!.address.trim().isEmpty()) {
                showToast("请输入详细地址")
                return@setOnClickListener
            }
            mViewModel.saveInfo()
        }
        mDatabind.nameEt.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(textView: TextView?, actionId: Int, keyEvent: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(textView!!.windowToken, 0)
                    return true
                }
                return false
            }

        })

        mDatabind.zyEt.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(textView: TextView?, actionId: Int, keyEvent: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(textView!!.windowToken, 0)
                    return true
                }
                return false
            }

        })


        mDatabind.addressEt.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(textView: TextView?, actionId: Int, keyEvent: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(textView!!.windowToken, 0)
                    return true
                }
                return false
            }

        })

//        mDatabind.avatarIv.load(App.userInfo.profile, builder = {
//            this.error(R.drawable.avatar_default)
//            this.placeholder(R.drawable.avatar_default)
//            transformations(RoundedCornersTransformation(dp2px(25).toFloat()))
//        })

        mDatabind.attendRg.setOnCheckedChangeListener { radioGroup, i ->
            run {
                val userInfo = mViewModel.userInfo.get()
                if (i == R.id.attendYesRb) {
                    userInfo?.has_participation = 1
                } else {
                    userInfo?.has_participation = 0
                }
                mViewModel.userInfo.set(userInfo)
            }
        }

        mDatabind.trainingRg.setOnCheckedChangeListener { radioGroup, i ->
            run {
                val userInfo = mViewModel.userInfo.get()
                if (i == R.id.trainingYesRb) {
                    userInfo?.has_exercise = 1
                } else {
                    userInfo?.has_exercise = 0
                }
                mViewModel.userInfo.set(userInfo)
            }
        }
        App.userInfo.credential_files?.let {
            certificaterAdapter.addData(it)
        }

        mDatabind.certificateRV.init(LinearLayoutManager(this, RecyclerView.VERTICAL, false), certificaterAdapter)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.address.observe(this){
            mViewModel.userInfo.get()!!.address  = it
        }
        mViewModel.saveResult.observe(this) {
            parseState(it, {
                showToast("保存成功")
                App.userInfo = mViewModel.userInfo.get()!!
                eventViewModel.userInfoChange.postValue(true)
                finish()
            }, {
                it.printStackTrace()
            }, {

            })
        }
        mViewModel.updatecertificaterAdapter.observe(this) {
            certificaterAdapter.setList(mViewModel.userInfo.get()?.credential_files)
        }
    }

    inner class ClickProxy {
        fun clickUpdateAvatar() {
            showTakePhotoPop(true)
        }

        fun clickEduation() {
            showPicker(arrayListOf("研究生", "大学", "大专", "高中", "初中以下"), "教育程度", mViewModel.userInfo.get()?.qualification)
        }

        fun clickWorkTime() {
            showPicker(arrayListOf("1年及以下", "2年", "3年", "4年", "5年", "6年", "7年", "8年", "9年", "10年", "10年以上"), "从业时长", mViewModel.userInfo.get()?.work_time)
        }

        fun clickAddress() {
            showAddressDialog()
        }

        fun clickBorn() {
            showBornDialog()
        }

        fun clickLocation() {
            if (ContextCompat.checkSelfPermission(this@UserinfoActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this@UserinfoActivity, arrayOf<String>(android.Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_LOCATION_PERMISSION)
            } else {
                location()
            }
        }

        fun clickAddCertificate() {
            showTakePhotoPop(false)
        }
    }

    fun showAddressDialog() {
        val picker = AddressPicker(this)
        picker.setBackgroundResource(R.drawable.bg_white_top_round_8)
        picker.setTitle("请选择")
        picker.okView.setTextColor(resources.getColor(R.color.colorAccent))
        picker.cancelView.setTextColor(resources.getColor(R.color.colorAccent))
        picker.titleView.setTextColor(Color.BLACK)
        picker.setDefaultValue(App.userInfo.province, App.userInfo.city, App.userInfo.district)
        picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
        picker.setOnAddressPickedListener { province, city, county ->
            mViewModel.userInfo.get()?.province = province.name
            mViewModel.userInfo.get()?.city = city.name
            mViewModel.userInfo.get()?.district = county.name
            mDatabind.provinceEt.setText("${province.name}-${city.name}-${county.name}")
        }
        picker.show()
    }

    fun showBornDialog() {
        if (!this@UserinfoActivity::birthdayPicker.isInitialized) {
            var year = "1970"
            var month = "1"
            var day = "1"
            if (App.userInfo.birthday.isNotEmpty() && App.userInfo.birthday.contains("-")) {
                year = App.userInfo.birthday.split("-")[0]
                month = App.userInfo.birthday.split("-")[1]
                day = App.userInfo.birthday.split("-")[2]
            }
            val currentDate = LocalDate.now()
            birthdayPicker = DatePicker(this)
            birthdayPicker.setBackgroundResource(R.drawable.bg_white_top_round_8)
            birthdayPicker.setTitle("出生日期")
            val wheelLayout = birthdayPicker.wheelLayout
            wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
            wheelLayout.setDateLabel("", "", "")
            wheelLayout.setRange(DateEntity.target(1928, 1, 1), DateEntity.target(currentDate.year, currentDate.monthValue, currentDate.dayOfMonth), DateEntity.today())
            wheelLayout.setDefaultValue(DateEntity.target(year.toInt(), month.toInt(), day.toInt()))
            wheelLayout.setDateFormatter(UnitDateFormatter())
            wheelLayout.setCurtainEnabled(false)
            wheelLayout.setIndicatorEnabled(false)
            birthdayPicker.wheelLayout.setResetWhenLinkage(false)
            birthdayPicker.setOnDatePickedListener(object : OnDatePickedListener {
                override fun onDatePicked(year: Int, month: Int, day: Int) {
                    mViewModel.userInfo.get()?.birthday = "${year}-${String.format("%02d", month)}-${String.format("%02d", day)}"
                    mViewModel.userInfo.notifyChange()
                }

            })
        }

        birthdayPicker.show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_LOCATION_PERMISSION) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                location()
            } else {
                // 权限被拒绝
                Toast.makeText(this, "位置权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun location() {
        if(!AppUtils.checkGPSIsOpen(this)){
            showNoLocationPop()
            return
        }
        showLoading("正在获取地理位置")
        TencentLocationManager.setUserAgreePrivacy(true)
        val mLocationManager = TencentLocationManager.getInstance(this)
        val request = TencentLocationRequest.create()
        request.isGpsFirst = true
        mLocationManager.requestSingleFreshLocation(request, object : TencentLocationListener {
            override fun onLocationChanged(location: TencentLocation?, p1: Int, p2: String?) {
                dismissLoading()
                location?.let {
                    if (it.city == null) {
                        appContext.showToast("获取定位数据失败")
                        return@let
                    }
                    mViewModel.userInfo.get()?.province = it.province
                    mViewModel.userInfo.get()?.city = it.city
                    mViewModel.userInfo.get()?.district = it.district
                    mViewModel.address.value = "${it.address + it.name}"
                    mViewModel.userInfo.get()?.address = "${it.address + it.name}"
                    mDatabind.provinceEt.setText("${it.province}-${it.city}-${it.district}")
                    mViewModel.userInfo.notifyChange()
                }
            }

            override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {

            }

        }, Looper.getMainLooper())
    }

    fun showTakePhotoPop(crop: Boolean) {
        val pop = XPopup.Builder(this).dismissOnTouchOutside(true).dismissOnBackPressed(true).isDestroyOnDismiss(true).autoOpenSoftInput(false).asCustom(TakePhotoPop(this, object : TakePhotoPop.Listener {
            override fun onclickItem(index: Int, pop: TakePhotoPop) {
                if (index == TakePhotoPop.TAKE_PHOTO) {
                    takePhoto(crop)
                } else if (index == TakePhotoPop.ALBUM) {
                    takeAlbum(crop)
                }
                pop.dismiss()
            }

        }))

        pop.show()
    }

    fun takePhoto(isAvatar: Boolean) {
        PictureSelector.create(this).openCamera(SelectMimeType.ofImage()).isOriginalSkipCompress(false).forResult(object : OnResultCallbackListener<LocalMedia?> {
            override fun onResult(result: ArrayList<LocalMedia?>) {
                println(result)
                if (isAvatar) {
                    result[0]?.realPath?.let { startCropActivity(it) }
                } else {
                    updateAvatar(result[0]?.realPath, false)
                }
            }

            override fun onCancel() {}
        })
    }

    fun takeAlbum(isAvatar: Boolean) {
        PictureSelector.create(this).openSystemGallery(SelectMimeType.ofImage()).setSelectionMode(SelectModeConfig.SINGLE).isOriginalSkipCompress(false).forSystemResult(object : OnResultCallbackListener<LocalMedia?> {
            override fun onResult(result: ArrayList<LocalMedia?>) {
                println(result)
                if (isAvatar) {
                    result[0]?.realPath?.let { startCropActivity(it) }
                } else {
                    updateAvatar(result[0]?.realPath, false)
                }
            }

            override fun onCancel() {

            }
        })
    }

    var mDestinationUri: File? = null
    fun startCropActivity(orinPath: String) {
        mDestinationUri = File(this.cacheDir, "/temp.jpg")
        val orinFile = File(orinPath)
        val option = UCrop.Options()
//        option.setToolbarTitleSize(dp2px(8))
        UCrop.of<Any>(Uri.fromFile(orinFile), Uri.fromFile(mDestinationUri)).withOptions(option).withAspectRatio(1f, 1f).withMaxResultSize(150, 150).start(this, UCrop.REQUEST_CROP)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == UCrop.REQUEST_CROP && resultCode == Activity.RESULT_OK) {
            mDatabind.avatarIv.load(mDestinationUri) {
                transformations(RoundedCornersTransformation(dp2px(33).toFloat()))
            }
            updateAvatar(mDestinationUri?.path, true)
        }
    }

    private fun updateAvatar(path: String?, isAvatar: Boolean) {
        var file: File = File(path)
        path?.let {
            // 获取图片类型
            val index = file.name.lastIndexOf(".");
            var fileType = file.name.substring(index + 1)
            if (fileType == "jpg") {
                fileType = "jpeg"
            }

            // 创建图片的Part
            val reqFile = RequestBody.create(MediaType.parse("image/" + fileType), file)
            val body = MultipartBody.Part.createFormData("file", file.name, reqFile)

            mViewModel.updateAvatar(body, isAvatar, file.name)

        }
    }


    fun showPicker(data: ArrayList<String>, title: String, defaultValue: String?) {
        var defaultIndex = 2
        data.forEachIndexed { index, s ->
            if (s == defaultValue) {
                defaultIndex = index
            }
        }

        val picker = OptionPicker(this)
        picker.setBackgroundResource(R.drawable.bg_white_top_round_8)
        picker.setTitle(title)
        picker.titleView.setTextColor(resources.getColor(R.color.black))
        picker.setData(data)
        picker.setDefaultPosition(defaultIndex)
        picker.setOnOptionPickedListener { position, item ->
            val userinfo = mViewModel.userInfo.get()
            mViewModel.userInfo.set(userinfo)
            if (title == "教育程度") {
                userinfo?.qualification = item.toString()
            } else {
                userinfo?.work_time = item.toString()
            }
            mViewModel.userInfo.set(userinfo)
            mViewModel.userInfo.notifyChange()
        }
        picker.show()
    }

}